package cn.xzchain.concurrency.singleton;

import cn.xzchain.concurrency.annoations.NotRecommend;
import cn.xzchain.concurrency.annoations.NotThreadSafe;
import cn.xzchain.concurrency.annoations.ThreadSafe;

/**
 * @author lihang
 * @date 2018/5/7.
 * @description 懒汉模式,双重坚持锁机制
 */
@NotThreadSafe
public class Singleton4 {

    private Singleton4(){
    }

    private static Singleton4 instance = null;


    // 1、memory = allocate() 分配对象的内存空间
    // 2、ctorInstance() 初始化对象
    // 3、instance = memory 设置instance指向刚分配的内存

    // JVM和cpu优化，发生了指令重排

    // 1、memory = allocate() 分配对象的内存空间
    // 3、instance = memory 设置instance指向刚分配的内存
    // 2、ctorInstance() 初始化对象


    /**静态工厂模式*/
    public static Singleton4 getInstance(){
        if (instance == null){
            synchronized (Singleton4.class){
                if (instance == null){
                    instance = new Singleton4();
                }
            }
        }
        return instance;
    }
}
